package com.istock.servicesample.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.istock.base.common.api.model.ApiBaseResponse;
import com.istock.base.common.api.model.RetStatusEnum;

@ControllerAdvice
public class GlobalExceptionHandler {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseBody
	public ApiBaseResponse<Void> validateException(HttpServletRequest request , HttpServletResponse response , MethodArgumentNotValidException exception) {
		logger.error("the controller valid variable fail " , exception);
		ApiBaseResponse<Void> apiResponse = new ApiBaseResponse<Void>();
		apiResponse.setCode("F00001");
		apiResponse.setStatus(RetStatusEnum.FAIL);
		apiResponse.setMessage(exception.getBindingResult().getFieldError().getDefaultMessage());
		return apiResponse;
	}
	
	
	@ExceptionHandler(Throwable.class)
	@ResponseBody
	public ApiBaseResponse<Void> exceptionHandler(HttpServletRequest request , HttpServletResponse response , Throwable throwable) {
		logger.error("global exception " , throwable);
		ApiBaseResponse<Void> apiResponse = new ApiBaseResponse<Void>();
		apiResponse.setCode("F");
		apiResponse.setStatus(RetStatusEnum.FAIL);
		apiResponse.setMessage(throwable.getMessage());
		return apiResponse;
	}
}
